import 'dart:async';
import 'dart:io';

import 'package:flutter_base_app/utils/permission_utils.dart';
import 'package:flutter_common_utils/common_utils_export.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image/image.dart' as img;
import 'package:image_picker/image_picker.dart';

class VkImageUtils {
  VkImageUtils._();

  /// 获取一个新的图片文件
  static Future<File> newImage() async {
    final appDir = File("${FileUtils.cacheDir}/vk/image_$currentTimeMillis.jpg");
    return appDir.createX();
  }

  ///拍照
  static Future<File?> takePhoto({bool isCompress = true}) async {
    // 检查相机权限
    if (await PermissionUtils.requestCameraPermission()) {
      final XFile? imageFile = await ImagePicker()
          .pickImage(source: ImageSource.camera, preferredCameraDevice: CameraDevice.rear);
      if (imageFile == null) {
        return null; //  取消
      }
      if (isCompress) {
        // 压缩图片
        return await compressImage(File(imageFile.path), autoCorrectionAngle: true);
      }
      return File(imageFile.path);
    }
    return null;
  }

  ///选择图片
  static Future<File?> selectPhoto({bool isCompress = true}) async {
    // 检查相机权限
    final XFile? imageFile = await ImagePicker()
        .pickImage(source: ImageSource.gallery, preferredCameraDevice: CameraDevice.rear);
    if (imageFile == null) {
      return null; //  取消
    }
    if (isCompress) {
      // 压缩图片
      return await compressImage(File(imageFile.path));
    }
    return File(imageFile.path);
  }

  ///压缩图片
  static Future<File> compressImage(
    File file, {
    //是否保存到父目录
    bool isSaveParent = true,
    bool autoCorrectionAngle = false,
    //是否自适应宽高
    bool autoWidthHeight = true,
    int minWidth = 1920,
    int minHeight = 1080,
  }) async {
    //自适应宽度
    if (autoWidthHeight) {
      try {
        final image = img.decodeImage(await file.readAsBytes());
        minWidth = image?.width ?? 1920;
        minHeight = image?.height ?? 1080;
      } catch (e) {
        LogUtils.e(e);
        minWidth = 1920;
        minHeight = 1080;
      }
    }
    final String targetPath = isSaveParent
        ? '${file.parent.path}/compressed_${file.uri.pathSegments.last}'
        : '${FileUtils.cacheDir}/compressed_${file.uri.pathSegments.last}';
    //打印原文件信息
    LogUtils.e("图片压缩前 ${file.path} ,length = ${await file.length()}");
    final XFile? result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      minWidth: minHeight,
      minHeight: minHeight,
      quality: 70, // 压缩质量 (0-100)
      autoCorrectionAngle: autoCorrectionAngle, // 自动校正方向
    );
    if (result == null) {
      return file;
    } else {
      //打印信息
      LogUtils.e("图片压缩成功 ${result.path} ,length = ${await result.length()}");
      return File(result.path);
    }
  }
}
